package com.youan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youan.bean.User;
import com.youan.dao.UserDao;
import com.youan.service.UserService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {
    @Resource
    UserDao dao;
    @Resource
    RedisTemplate redisTemplate;
    String rName = "redis:";

    @Override
    public String addUser(User user) {
        if (user.getName() == null) {
            return "姓名不能为空";
        } else {
            int i = dao.insert(user);
            redisTemplate.setKeySerializer(new StringRedisSerializer());
            redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer(User.class));
            redisTemplate.opsForValue().set(rName + user.getName(), user);
            return "添加用户成功, " + user;
        }
    }

    @Override
    public List<User> listAllUsers() {
        return dao.selectList(null);
    }

    @Override
    public Map<Integer, Object> selectUserByRName(String name) {
        Map<Integer, Object> map = new HashMap<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer(User.class));
        if (name == null || "".equals(name)) {
            redisTemplate.opsForValue().set(rName + "000", null, 3, TimeUnit.SECONDS);
            return null;
        } else {
            User user = (User) redisTemplate.opsForValue().get(rName + name);
            if (user != null) {
                map.put(1, user);
                map.put(2, "从redis获取数据");
                return map;
            } else {
                User user1 = dao.selectByName(name);
                if (user1 != null) {
                    redisTemplate.opsForValue().set(rName + name, user1);
                    System.out.println("从数据库获取数据" + user1);
                    map.put(1, user1);
                    map.put(2, "从数据库获取数据");
                    return map;
                } else {
                    return null;
                }
            }
        }
    }
}
